<template>
  <DFModal
    ref="dfModal"
    class="unitOptions-modal basicModal"
    :width="1200"
    @register="modalRegister"
    @on-ok="okModalFn"
  >
    <template #default>
      <div class="flex img-swiper">
        <div class="center-view-left-img">
          <n-carousel
            v-if="imgList.length > 1"
            autoplay
            show-arrow
            show-dots
            draggable
            dot-type="dot"
          >
            <n-image
              v-for="(item, key) in imgList"
              :key="key"
              :src="item"
              :fallback-src="paper6"
              object-fit="contain"
              preview-disabled
              :img-props="{ style: { display: 'block', cursor: 'pointer' } }"
            />
          </n-carousel>

          <n-image
            v-else
            :src="imgList.length ? imgList[0] : paper6"
            object-fit="contain"
            :fallback-src="paper6"
            preview-disabled
            :img-props="{ style: { display: 'block', cursor: 'pointer' } }"
          />
        </div>
      </div>

      <DFTable
        ref="dfTable"
        :route-name="routeName"
        :columns="tableColumns"
        :row-key="(row) => row.uuid"
        :pagination="false"
        :checked-row-key-model="true"
      />
    </template>
  </DFModal>
</template>

<script lang="ts" setup>
  import { DFModal, useModal } from '@/components/DFModal';

  import { DFTable } from '@/components/DFTable';

  import { useMixins } from '@/hooks/useMixins';

  import { renderSvg } from '@/utils/index';

  import Sortable from 'sortablejs';

  import paper6 from '@/assets/images/paper6.png';

  import { NColorPicker } from 'naive-ui';

  import { v4 as uuidv4 } from 'uuid';
  import { saveParameterUnitByMaterialVersion } from '@render/api/base/material';
  import { listColor } from '@render/api/base/color';
  import { listPlate } from '@render/api/base/plate';
  import { generateRandomValue } from '@/utils/index';

  interface Props {
    imgList?: any;
    machine?: any;
    parameterUnitList?: any;
    chooseItem?: any;
    routeName?: string;
  }

  const emit = defineEmits(['distributionFn', 'getParameterUnitByMaterialVersionFn', 'register']);

  const props = withDefaults(defineProps<Props>(), {
    imgList: () => [],
    machine: () => null,
    parameterUnitList: () => [],
    chooseItem: () => null,
    routeName:()=> 'productionCenter',
  });

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});

  const { message, t } = useMixins();

  const printUnitObj = ref(null);

  const colorList = ref([]);

  const plateList = ref([]);

  const tableColumns = [
    {
      label: 'printUnit',
      key: 'printUnit',
      width: 120,
      render: (row) => {
        return h('span', {
          innerText: `${t(props.routeName+'.table.printUnit')} ${row.printUnit}`,
        });
      },
    },
    {
      label: 'plate',
      key: 'plateId',
      width: 180,
      edit: true,
      itemData: {
        component: 'NSelect',
        componentProps: {
          filterable: true,
          options: plateList,
          tag: true,
          // "render-label": (option: SelectOption) => {
          //   const { customCode, customShort } = option || {};
          //   return `${customShort}${customCode ? `(${customCode})` : ''}`
          // },
          'on-create': (label: string) => {
            const data = { label, value: generateRandomValue(16), id: uuidv4() };

            return data;
          },
          onUpdateValue: (_v: string, option: any, updateFormModelFn: any) => {
            if (updateFormModelFn && option) {
              const { value = null, label = null, plateCode = null } = option;

              const data: any = {
                plateCode,
                plateName: label,
                plateId: value,
              };

              typeof updateFormModelFn === 'function' && updateFormModelFn(data);
            } else {
              typeof updateFormModelFn === 'function' &&
                updateFormModelFn({
                  plateCode: null,
                  plateName: null,
                  plateId: null,
                });
            }
          },
        },
      },
    },
    {
      label: 'colorName',
      key: 'colorId',
      required: true,
      edit: true,
      width: 180,
      itemData: {
        component: 'NSelect',
        componentProps: {
          options: colorList,
          filterable: true,
          tag: true,
          // "render-label": (option: SelectOption) => {
          //   const { customCode, customShort } = option || {};
          //   return `${customShort}${customCode ? `(${customCode})` : ''}`
          // },
          'on-create': (label: string) => {
            const data = { label, value: uuidv4(), color: null, colorModel: null };

            // colorList.value.push(data);

            return data;
          },
          onUpdateValue: (_v: string, option: any, updateFormModelFn: any) => {
            if (updateFormModelFn && option) {
              const { value = null, color = null, colorModel = null, label = null } = option;

              const data: any = {
                colorId: value,
                color,
                colorModel,
                colorName: label,
              };

              typeof updateFormModelFn === 'function' && updateFormModelFn(data);
            } else {
              typeof updateFormModelFn === 'function' &&
                updateFormModelFn({
                  colorId: null,
                  color: null,
                  colorModel: null,
                  colorName: null,
                });
            }
          },
        },
      },
    },
    {
      label: 'color',
      key: 'color',
      width: 180,
      render: (row) => {
        return h(NColorPicker, {
          'show-preview': true,
          value: row.color,
          'on-update:value': (val) => {
            row.color = val;
          },
        });
      },
    },
    {
      label: 'colorModel',
      key: 'colorModel',
      edit: true,
      width: 180,
      itemData: {
        component: 'NInput',
      },
    },
    {
      label: 'sort',
      common: true,
      sorter: false,
      align: 'center',
      fixed: 'right',
      className: 'sort-column',
      // title() {
      //   return h('div', {
      //     class: '123123123',
      //     width: '100%',
      //     'text-align': 'center',
      //     innerText: t(`common.table.sort`),
      //   });
      // },
      render(_row) {
        return h(renderSvg('fixedModalSort'), { class: 'fixed-modal-sort' });
      },
    },
  ];

  const list: any = ref([]);

  const dfTable = ref(null);

  async function openModalFn() {
    const { machine, parameterUnitList, chooseItem } = props;

    list.value = [];

    const [res1, res2] = await Promise.all([listColor(), listPlate()]);

    colorList.value = (res1.data || []).map((item) => {
      return {
        label: item.colorName,
        value: item.id,
        colorModel: item.colorModel,
        color: item.color,
      };
    });

    plateList.value = (res2.data || []).map((item) => {
      return {
        label: item.plateName,
        value: item.id,
        plateCode: item.plateCode,
      };
    });

    if (machine && chooseItem) {
      const { unitNum } = machine;

      printUnitObj.value = {};

      if (parameterUnitList.length) {
        list.value = parameterUnitList
          .sort((a, b) => a.printUnit - b.printUnit)
          .map((item, key) => {
            printUnitObj.value[key] = item.printUnit;

            return {
              index: key + 1,
              ...item,
              colorModel:colorList.value.find((c) => c.value === item.colorId)?.colorModel || null,
              uuid: uuidv4(),
            };
          });

        if (parameterUnitList.length < unitNum) {
          for (let i = 0; i < unitNum - parameterUnitList.length; i++) {
            printUnitObj.value[list.value.length] = list.value.length;

            list.value.push({
              index: list.value.length,
              printUnit: list.value.length,
              plateCode: null,
              plateName: null,
              plateId: null,
              color: null,
              colorId: null,
              colorModel: null,
              colorName: null,
              uuid: uuidv4(),
            });
          }
        }
      } else {
        for (let i = 0; i < unitNum; i++) {
          printUnitObj.value[i + 1] = i + 1;

          list.value.push({
            index: i + 1,
            printUnit: i + 1,
            plateCode: null,
            plateName: null,
            plateId: null,
            color: null,
            colorId: null,
            colorModel: null,
            colorName: null,
            uuid: uuidv4(),
          });
        }
      }

      openModal(null, t(`${props.routeName}.table.unitOptions`));

      nextTick(() => {
        dfTable.value && dfTable.value.setTableData(list.value);

        nextTick(() => {
          // 需要支持拖动效果的列表容器，在这里我们设置为el-table组件的tbody，
          // 注意：最前面的一段为前面el-table的class: draggable-table，主要为了防止如果页面有多个table，多个table同时实现拖拽效果
          // 当然，如果多个table都需要拖拽效果，选择器中最前面的.draggable-table可以去除。
          const tbody = document.querySelector('.unitOptions-modal .n-data-table-tbody');

          new Sortable(tbody, {
            animation: 150,
            handle: '.fixed-modal-sort',
            filter: '.no-draggable',
            invertSwap: false,
            preventOnFilter: true,
            onSort(/** Event */ _evt) {
              // console.log('sort',evt)
              // 与 onEnd 相同的属性
            },
            onChange(_e, _a, _c) {
              // console.log('change',e)
              // console.log(a)
              // if(e.newIndex === 2){
              //   return false
              // }
            },
            onMove(/** Event */ _evt, /** Event */ _originalEvent) {
              // console.log('move',evt)
              // console.log(originalEvent)
              // if(evt.newIndex === 2){
              //   return false
              // }
              // return false
            },
            // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
            onEnd: ({ newIndex, oldIndex }) => {
              // console.log(newIndex)

              // console.log(oldIndex)

              const targetRow = list.value[oldIndex];
              list.value.splice(oldIndex, 1);
              list.value.splice(newIndex, 0, targetRow);

              list.value.forEach((item, key) => {
                item.index = key + 1;

                printUnitObj.value[item.printUnit] = key + 1;
              });

              // console.table(this.dialogTableDataList);
            },
          });
        });

        // console.log(dfTable.value);
      });
    }
  }

  async function okModalFn() {
    try {
      // modalSubmitFn()

      const { chooseItem, machine } = props;

      const { machineCode } = machine;

      const { materialCode, version } = chooseItem;

      const dataList = unref(list).map((item, key) => {
        return { ...item, printUnit: key + 1, machineCode, materialCode, version };
      });

      await saveParameterUnitByMaterialVersion({
        machineCode,
        materialCode,
        version,
        list: dataList,
      });

      message.success(t('common.tipMsg.isSucc'));

      emit('distributionFn', props.parameterUnitList.length ? printUnitObj.value : null);

      emit('getParameterUnitByMaterialVersionFn');

      closeModal();
    } catch (e) {
      console.log(e);
    }

    nextTick(() => {
      setSubLoading(false);
    });
  }

  defineExpose({
    openModalFn,
  });
</script>

<style lang="less">
  .unitOptions-modal {
    .img-swiper {
      justify-content: center;
      height: 298px;
      margin-bottom: 16px;
      .n-image,
      img {
        width: 100%;
      }
    }
    .fixed-modal-sort {
      width: 18px;
      height: 18px;
      margin: 0 auto;
      cursor: move;
    }
  }
  .sort-column > .n-data-table-th__title-wrapper {
    justify-content: space-around;
  }
</style>
